package cn.lg.soar.mvc.config;

import cn.lg.soar.mvc.model.CorsProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.Filter;
import java.util.List;

/**
 * 枚举转换器注册
 * @author luguoxiang
 * @date 2022/9/5
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Configuration
@ConditionalOnProperty(value = "lg.mvc.cors.enabled", havingValue = "true")
public class CorsConfiguration implements WebMvcConfigurer {

    @Autowired
    private CorsProperties corsProperties;

    @Bean
    public FilterRegistrationBean<Filter> corsFilter() {
        FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();

        org.springframework.web.cors.CorsConfiguration corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
        //允许的域名
        corsConfiguration.setAllowedOrigins(corsProperties.getOrigins());
        //允许的头
        corsConfiguration.setAllowedHeaders(corsProperties.getHeaders());
        //允许的方法
        corsConfiguration.setAllowedMethods(corsProperties.getMethods());
        //有效期
        corsConfiguration.setMaxAge(corsProperties.getAge());

        List<String> mappings = corsProperties.getMappings();
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        for(String mapping: mappings){
            source.registerCorsConfiguration(mapping, corsConfiguration);
        }

        registrationBean.setFilter(new CorsFilter(source));
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return registrationBean;
    }

}
